import pymongo
import configparser
import os
import download_javbook.check_is_all as d

CONNECTION_STR = 'mongodb://192.168.0.196:27017/?readPreference=primary&appname=MongoDB%20Compass%20Community&ssl=false'

# 读取配置
cf = configparser.ConfigParser()
cf.read(os.path.dirname(os.path.abspath('.')) + '/download_javbook/config.ini')
DATA_BASE = cf.get('javbook', 'DATA_BASE')
DB_COL = cf.get('javbook', 'DB_COL')
SERIES = cf.get('javbook', 'SERIES')
YEAR = cf.get('javbook', 'YEAR')


# 根据nums_list查出tor
def get_nums_list():
    ans_check_temp = d.check_in_database(d.PATH)
    ans_check = []
    for a in ans_check_temp:
        ans_check.append(a['num'])
    return ans_check


def query_tor_by_nums(nums_list):
    # 连接数据库
    db_client = pymongo.MongoClient(CONNECTION_STR)
    db_database = db_client[DATA_BASE]
    db_col = db_database[DB_COL]

    ans = []
    for num in nums_list:
        # 查询出全集
        query = {'series': SERIES, 'num': num}
        query_ans = list(db_col.find(query))
        if len(query_ans) == 0:
            print('没有找到：{}'.format(num))
        if len(query_ans) == 1:
            ans.append(query_ans[0]['tor'])
            print('找到：{},tor:{},url:{}'.format(num, query_ans[0]['tor'], query_ans[0]['detail_url']))

    db_client.close()
    return ans


# 根据year查询出所有tor和没有tor的num_list:
def check_tor_by_year():
    # 连接数据库
    db_client = pymongo.MongoClient(CONNECTION_STR)
    db_database = db_client[DATA_BASE]
    db_col = db_database[DB_COL]

    query = {'series': SERIES, 'year': YEAR}
    query_ans = list(db_col.find(query))

    if len(query_ans) == 0:
        print('没有找到')
    else:
        count = 1
        for q in query_ans:
            if q['tor'] != '':
                if count % 20 == 0:
                    print('\n')
                print(q['tor'])
                count = count + 1
    print('共有{}个'.format(len(query_ans)))

    db_client.close()


if __name__ == '__main__':
    # # 根据nums_list查出tor
    # ans_check = get_nums_list()
    # ans = query_tor_by_nums(ans_check)

    # 根据year查询出所有tor
    check_tor_by_year()
